import axios, { AxiosError } from 'axios'

// API base URL from environment or fallback
const API_BASE_URL = import.meta.env.VITE_API_URL || '/api/v1'

// Create axios instance with default config
const apiClient = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

// Request interceptor to add token
apiClient.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// Response interceptor for error handling
apiClient.interceptors.response.use(
  (response) => response,
  (error: AxiosError) => {
    if (error.response?.status === 401) {
      // Token expired or invalid
      localStorage.removeItem('token')
      localStorage.removeItem('user-storage')
      window.location.href = '/auth/login'
    }
    return Promise.reject(error)
  }
)

// API response types
interface ApiResponse<T = any> {
  success: boolean
  data?: T
  message?: string
  error?: {
    code: string
    message: string
  }
}

interface LoginResponse {
  user: {
    id: string
    email: string
    username: string
    role: string
    createdAt: string
    updatedAt: string
  }
  token: string
  refreshToken?: string
}

interface RegisterResponse {
  user: {
    id: string
    email: string
    username: string
    role: string
    createdAt: string
    updatedAt: string
  }
  message: string
}

export const authService = {
  /**
   * User login
   */
  async login(email: string, password: string, remember: boolean = false): Promise<LoginResponse> {
    // 模拟登录 - 直接判断 admin/admin
    if ((email === 'admin' || email === 'admin@example.com') && password === 'admin') {
      const mockUser = {
        id: '1',
        email: 'admin@example.com',
        username: 'admin',
        role: 'admin',
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString()
      }
      
      const mockToken = 'mock-jwt-token-' + Date.now()
      
      // 存储token
      localStorage.setItem('token', mockToken)
      
      // 设置过期时间
      if (remember) {
        const expiryDate = new Date()
        expiryDate.setDate(expiryDate.getDate() + 30)
        localStorage.setItem('tokenExpiry', expiryDate.toISOString())
      } else {
        const expiryDate = new Date()
        expiryDate.setHours(expiryDate.getHours() + 24)
        localStorage.setItem('tokenExpiry', expiryDate.toISOString())
      }
      
      return {
        user: mockUser,
        token: mockToken,
        refreshToken: 'mock-refresh-token-' + Date.now()
      }
    }
    
    // 如果不是 admin/admin，尝试调用真实API
    try {
      const response = await apiClient.post<ApiResponse<LoginResponse>>('/auth/login', {
        email,
        password,
      })

      if (response.data.success && response.data.data) {
        const { token, refreshToken } = response.data.data
        
        // Store token with expiry based on remember option
        if (remember) {
          // Set longer expiry for "remember me" (30 days)
          const expiryDate = new Date()
          expiryDate.setDate(expiryDate.getDate() + 30)
          localStorage.setItem('tokenExpiry', expiryDate.toISOString())
        } else {
          // Set session expiry (24 hours)
          const expiryDate = new Date()
          expiryDate.setHours(expiryDate.getHours() + 24)
          localStorage.setItem('tokenExpiry', expiryDate.toISOString())
        }

        // Store refresh token if provided
        if (refreshToken) {
          localStorage.setItem('refresh_token', refreshToken)
        }

        return response.data.data
      }

      throw new Error(response.data.error?.message || '登录失败')
    } catch (error) {
      // 如果是网络错误或404，提示使用 admin/admin 登录
      if (axios.isAxiosError(error)) {
        if (error.code === 'ERR_NETWORK' || error.response?.status === 404) {
          throw new Error('服务暂不可用，请使用 admin/admin 登录')
        }
        if (error.response?.data) {
          const errorData = error.response.data as ApiResponse
          throw new Error(errorData.error?.message || '登录失败')
        }
      }
      throw new Error('网络错误，请使用 admin/admin 登录')
    }
  },

  /**
   * User registration
   */
  async register(data: {
    email: string
    username: string
    password: string
  }): Promise<RegisterResponse> {
    try {
      const response = await apiClient.post<ApiResponse<RegisterResponse>>('/auth/register', data)

      if (response.data.success && response.data.data) {
        return response.data.data
      }

      throw new Error(response.data.error?.message || '注册失败')
    } catch (error) {
      if (axios.isAxiosError(error) && error.response?.data) {
        const errorData = error.response.data as ApiResponse
        throw new Error(errorData.error?.message || '注册失败')
      }
      throw error
    }
  },

  /**
   * Forgot password - send verification code
   */
  async forgotPassword(email: string): Promise<{ message: string }> {
    try {
      const response = await apiClient.post<ApiResponse>('/auth/forgot-password', { email })

      if (response.data.success) {
        return { message: response.data.message || '验证码已发送' }
      }

      throw new Error(response.data.error?.message || '发送失败')
    } catch (error) {
      if (axios.isAxiosError(error) && error.response?.data) {
        const errorData = error.response.data as ApiResponse
        throw new Error(errorData.error?.message || '发送失败')
      }
      throw error
    }
  },

  /**
   * Reset password with verification code
   */
  async resetPassword(data: {
    email: string
    code: string
    password: string
  }): Promise<{ message: string }> {
    try {
      const response = await apiClient.post<ApiResponse>('/auth/reset-password', data)

      if (response.data.success) {
        return { message: response.data.message || '密码重置成功' }
      }

      throw new Error(response.data.error?.message || '重置失败')
    } catch (error) {
      if (axios.isAxiosError(error) && error.response?.data) {
        const errorData = error.response.data as ApiResponse
        throw new Error(errorData.error?.message || '重置失败')
      }
      throw error
    }
  },

  /**
   * Refresh token
   */
  async refreshToken(): Promise<{ token: string; refreshToken?: string }> {
    const refreshToken = localStorage.getItem('refresh_token')
    if (!refreshToken) {
      throw new Error('No refresh token available')
    }

    try {
      const response = await apiClient.post<ApiResponse<{ token: string; refreshToken?: string }>>(
        '/auth/refresh',
        { refreshToken }
      )

      if (response.data.success && response.data.data) {
        return response.data.data
      }

      throw new Error(response.data.error?.message || 'Token刷新失败')
    } catch (error) {
      if (axios.isAxiosError(error) && error.response?.data) {
        const errorData = error.response.data as ApiResponse
        throw new Error(errorData.error?.message || 'Token刷新失败')
      }
      throw error
    }
  },

  /**
   * Logout
   */
  async logout(): Promise<void> {
    try {
      await apiClient.post('/auth/logout')
    } catch (error) {
      // Even if logout fails on server, clear local storage
      console.error('Logout error:', error)
    } finally {
      localStorage.removeItem('token')
      localStorage.removeItem('refresh_token')
      localStorage.removeItem('tokenExpiry')
      localStorage.removeItem('user-storage')
    }
  },

  /**
   * Check if token is expired
   */
  isTokenExpired(): boolean {
    const expiry = localStorage.getItem('tokenExpiry')
    if (!expiry) return true
    return new Date() > new Date(expiry)
  },
}